﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Data.SQLite;
using WebsiteStructureAnalyzer;

namespace Sec_scan安全漏洞扫描系统_2._0.HomeForm
{
    public partial class Home : Form
    {
        private string dbPath;

        public Home()
        {
            InitializeComponent();
            // 居中显示
            StartPosition = FormStartPosition.CenterScreen;
        }

        private void Home_Load(object sender, EventArgs e)
        {
            // 基带内存
            label2.Text = Services.Tl_SystemInfo.GetPhysicalMemoryInfo();
            // 处理器信息
            label3.Text = Services.Tl_SystemInfo.GetProcessorInfo();
            // 设备ID信息
            label5.Text = Services.Tl_SystemInfo.GetDeviceID();

            //Console.WriteLine("基带内存:");
            //Console.WriteLine(Services.Tl_SystemInfo.GetPhysicalMemoryInfo());
            //Console.WriteLine();

            //label3.Text = Services.Tl_SystemInfo.GetProcessorInfo();
            //Console.WriteLine("处理器:");
            //Console.WriteLine(Services.Tl_SystemInfo.GetProcessorInfo());
            //Console.WriteLine();

            //label5.Text = Services.Tl_SystemInfo.GetDeviceID();
            //Console.WriteLine("设备 ID:");
            //Console.WriteLine(Services.Tl_SystemInfo.GetDeviceID());

            // 加载数据
            SetupDataGridView();
            // 连接数据库
            LoadDataFromDatabase();
        }
        private void SetupDataGridView()
        {
            dataGridView1.Columns.Clear();
            dataGridView1.Rows.Clear();

            dataGridView1.Dock = DockStyle.Fill;
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.AllowUserToAddRows = false;
            dataGridView1.RowHeadersVisible = false;
            dataGridView1.ReadOnly = true;
            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dataGridView1.BackgroundColor = Color.White;
            dataGridView1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            // 选中后的颜色欠点
            dataGridView1.DefaultCellStyle.SelectionBackColor = Color.FromArgb(200, 220, 255);  // 浅蓝色背景
            dataGridView1.DefaultCellStyle.SelectionForeColor = Color.Black;  // 黑色文字

            // 移除选中时的边框
            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dataGridView1.DefaultCellStyle.SelectionBackColor = Color.FromArgb(240, 240, 255);
            dataGridView1.RowHeadersDefaultCellStyle.SelectionBackColor = Color.FromArgb(240, 240, 255);

            // 更改指针样式
            dataGridView1.CellMouseMove += DataGridView1_CellMouseMove;
            dataGridView1.MouseLeave += DataGridView1_MouseLeave;


            dataGridView1.GridColor = Color.White;
            dataGridView1.CellBorderStyle = DataGridViewCellBorderStyle.None;
            dataGridView1.BorderStyle = BorderStyle.None;

            dataGridView1.ColumnHeadersDefaultCellStyle = new DataGridViewCellStyle
            {
                Alignment = DataGridViewContentAlignment.MiddleCenter,
                BackColor = Color.LightGray,
                Font = new Font("Microsoft Sans Serif", 9F, FontStyle.Bold, GraphicsUnit.Point)
            };

            dataGridView1.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;
            dataGridView1.EnableHeadersVisualStyles = false;

            // 添加列
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn { Name = "TaskId", HeaderText = "任务ID", Width = 80 });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn { Name = "TaskName", HeaderText = "任务名称", Width = 150 });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn { Name = "TaskType", HeaderText = "任务类型", Width = 120 });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn { Name = "TaskStatus", HeaderText = "任务状态", Width = 100 });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn { Name = "Actions", HeaderText = "操作", Width = 200 });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn { Name = "Progress", HeaderText = "任务进度", Width = 150 });

            dataGridView1.CellClick += DataGridView1_CellClick;
            dataGridView1.CellPainting += DataGridView1_CellPainting;
            dataGridView1.CellFormatting += DataGridView1_CellFormatting;

            // 自适应大小
            SetupAutoSizeColumns();
        }
        private void DataGridView1_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex < 0 || e.ColumnIndex != dataGridView1.Columns["Actions"].Index)
            {
                dataGridView1.Cursor = Cursors.Default;
                return;
            }

            var row = dataGridView1.Rows[e.RowIndex];
            var buttonRects = row.Cells["Actions"].Tag as Dictionary<string, Rectangle>;

            if (buttonRects != null)
            {
                Point mousePoint = dataGridView1.PointToClient(Cursor.Position);

                // 检查鼠标是否在任意按钮上
                if (buttonRects["Start"].Contains(mousePoint) ||
                    buttonRects["Stop"].Contains(mousePoint) ||
                    buttonRects["Delete"].Contains(mousePoint))
                {
                    dataGridView1.Cursor = Cursors.Hand;  // 手型指针
                }
                else
                {
                    dataGridView1.Cursor = Cursors.Default;
                }
            }
        }

        private void DataGridView1_MouseLeave(object sender, EventArgs e)
        {
            dataGridView1.Cursor = Cursors.Default;
        }

        // 设置自适应列宽
        private void SetupAutoSizeColumns()
        {
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
            dataGridView1.Columns["TaskId"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            dataGridView1.Columns["TaskName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            dataGridView1.Columns["TaskType"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            dataGridView1.Columns["TaskStatus"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            dataGridView1.Columns["Actions"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            dataGridView1.Columns["Progress"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

            dataGridView1.Columns["TaskId"].MinimumWidth = 60;
            dataGridView1.Columns["TaskName"].MinimumWidth = 120;
            dataGridView1.Columns["TaskType"].MinimumWidth = 80;
            dataGridView1.Columns["TaskStatus"].MinimumWidth = 80;
            dataGridView1.Columns["Actions"].MinimumWidth = 150;
            dataGridView1.Columns["Progress"].MinimumWidth = 100;
        }
        private string GetDbPath()
        {
            // 获取应用程序启动目录
            string startupPath = Application.StartupPath;
            // 组合路径
            return Path.Combine(startupPath, "Db", "home.db");
        }
        // 从数据库加载数据
        private void LoadDataFromDatabase()
        {
            try
            {
                //CheckSQLiteDependencies();

                string dbPath = GetDbPath();

                // 检查数据库文件是否存在
                if (!File.Exists(dbPath))
                {
                    MessageBox.Show($"数据库文件不存在: {dbPath}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 连接字符串 - 在连接时动态获取路径
                string connectionString = $"Data Source={dbPath};Version=3;";

                using (var connection = new SQLiteConnection(connectionString))
                {
                    connection.Open();
                    Console.Write("连接到数据库");

                    // 读取task_list表数据
                    string query = "SELECT id, task_name, task_type, task_status FROM task_list";
                    using (SQLiteCommand command = new SQLiteCommand(query, connection))
                    {
                        using (SQLiteDataReader reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                int id = reader.GetInt32(0);
                                string taskName = reader.GetString(1);
                                string taskType = reader.GetString(2);
                                string taskStatus = reader.GetString(3);

                                dataGridView1.Rows.Add(
                                    id,
                                    taskName,
                                    taskType,
                                    taskStatus,
                                    "",  // 操作列
                                    0    // 进度
                                );
                            }
                        }
                    }
                }

                //MessageBox.Show($"成功加载 {dataGridView1.Rows.Count} 条任务数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void DataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;

            var row = dataGridView1.Rows[e.RowIndex];
            int taskId = Convert.ToInt32(row.Cells["TaskId"].Value);
            string taskName = row.Cells["TaskName"].Value.ToString();
            string taskStatus = row.Cells["TaskStatus"].Value.ToString();

            // 操作列点击
            if (e.ColumnIndex == dataGridView1.Columns["Actions"].Index)
            {
                var buttonRects = row.Cells["Actions"].Tag as Dictionary<string, Rectangle>;
                if (buttonRects != null)
                {
                    Point clickPoint = dataGridView1.PointToClient(Cursor.Position);

                    if (buttonRects["Start"].Contains(clickPoint) &&
                        (taskStatus == "等待中" || taskStatus == "已暂停"))
                    {
                        StartTask(row, taskId, taskName);
                    }
                    else if (buttonRects["Stop"].Contains(clickPoint) && taskStatus == "进行中")
                    {
                        StopTask(row, taskId, taskName);
                    }
                    else if (buttonRects["Delete"].Contains(clickPoint) && taskStatus != "进行中")
                    {
                        DeleteTask(row, taskId, taskName);
                    }

                    dataGridView1.InvalidateCell(dataGridView1.Columns["Actions"].Index, e.RowIndex);
                }
            }
        }

        private void StartTask(DataGridViewRow row, int taskId, string taskName)
        {
            row.Cells["TaskStatus"].Value = "进行中";
            StartProgressSimulation(row, taskId);
            MessageBox.Show($"已启动任务: {taskName}", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void StopTask(DataGridViewRow row, int taskId, string taskName)
        {
            row.Cells["TaskStatus"].Value = "已暂停";
            MessageBox.Show($"已停止任务: {taskName}", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void DeleteTask(DataGridViewRow row, int taskId, string taskName)
        {
            var result = MessageBox.Show($"确定要删除任务 '{taskName}' 吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                if (DeleteTaskFromDatabase(taskId))
                {
                    dataGridView1.Rows.Remove(row);
                    MessageBox.Show($"已删除任务: {taskName}", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        // 从数据库删除任务
        private bool DeleteTaskFromDatabase(int taskId)
        {
            try
            {
                string dbPath = GetDbPath();
                string connectionString = $"Data Source={dbPath};Version=3;";

                using (SQLiteConnection connection = new SQLiteConnection(connectionString))
                {
                    connection.Open();
                    string query = "DELETE FROM task_list WHERE id = @id";
                    using (SQLiteCommand command = new SQLiteCommand(query, connection))
                    {
                        command.Parameters.AddWithValue("@id", taskId);
                        int result = command.ExecuteNonQuery();
                        return result > 0;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除任务时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }

        // 绘制操作列和进度列
        private void DataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            // 操作列绘制
            if (e.RowIndex >= 0 && e.ColumnIndex == dataGridView1.Columns["Actions"].Index)
            {
                e.PaintBackground(e.CellBounds, true);

                var row = dataGridView1.Rows[e.RowIndex];
                string taskStatus = row.Cells["TaskStatus"].Value?.ToString() ?? "";

                int buttonWidth = 45;
                int buttonHeight = 25;
                int spacing = 8;
                int totalWidth = (buttonWidth * 3) + (spacing * 2);
                int startX = e.CellBounds.X + (e.CellBounds.Width - totalWidth) / 2;
                int buttonY = e.CellBounds.Y + (e.CellBounds.Height - buttonHeight) / 2;

                Rectangle startButtonRect = new Rectangle(startX, buttonY, buttonWidth, buttonHeight);
                Rectangle stopButtonRect = new Rectangle(startX + buttonWidth + spacing, buttonY, buttonWidth, buttonHeight);
                Rectangle deleteButtonRect = new Rectangle(startX + (buttonWidth + spacing) * 2, buttonY, buttonWidth, buttonHeight);

                bool canStart = taskStatus == "等待中" || taskStatus == "已暂停";
                bool canStop = taskStatus == "进行中";
                bool canDelete = taskStatus != "进行中";

                DrawButton(e.Graphics, startButtonRect, "启动", canStart);
                DrawButton(e.Graphics, stopButtonRect, "停止", canStop);
                DrawButton(e.Graphics, deleteButtonRect, "删除", canDelete);

                row.Cells["Actions"].Tag = new Dictionary<string, Rectangle>
                {
                    { "Start", startButtonRect },
                    { "Stop", stopButtonRect },
                    { "Delete", deleteButtonRect }
                };

                e.Handled = true;
            }

            // 进度列绘制
            else if (e.RowIndex >= 0 && e.ColumnIndex == dataGridView1.Columns["Progress"].Index)
            {
                e.PaintBackground(e.CellBounds, true);

                if (e.Value != null && int.TryParse(e.Value.ToString(), out int progress))
                {
                    Rectangle progressRect = new Rectangle(
                        e.CellBounds.X + 1,
                        e.CellBounds.Y + 1,
                        e.CellBounds.Width - 2,
                        e.CellBounds.Height - 2
                    );

                    int filledWidth = (int)(progressRect.Width * progress / 100.0);
                    Rectangle filledRect = new Rectangle(progressRect.X, progressRect.Y, filledWidth, progressRect.Height);

                    using (Brush bgBrush = new SolidBrush(Color.FromArgb(240, 240, 240)))
                        e.Graphics.FillRectangle(bgBrush, progressRect);

                    if (progress > 0)
                    {
                        using (Brush progressBrush = new SolidBrush(GetProgressColor(progress)))
                            e.Graphics.FillRectangle(progressBrush, filledRect);
                    }

                    using (Pen borderPen = new Pen(Color.FromArgb(200, 200, 200)))
                        e.Graphics.DrawRectangle(borderPen, progressRect);

                    string progressText = $"{progress}%";
                    Color textColor = progress > 50 ? Color.White : Color.Black;
                    TextRenderer.DrawText(e.Graphics, progressText, dataGridView1.Font,
                        e.CellBounds, textColor,
                        TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
                }

                e.Handled = true;
            }
        }

        // 绘制按钮
        private void DrawButton(Graphics g, Rectangle rect, string text, bool enabled)
        {
            Color textColor = enabled ? Color.Black : Color.LightGray;
            using (Brush textBrush = new SolidBrush(textColor))
            {
                StringFormat format = new StringFormat
                {
                    Alignment = StringAlignment.Center,
                    LineAlignment = StringAlignment.Center
                };
                g.DrawString(text, dataGridView1.Font, textBrush, rect, format);
            }

            if (!enabled)
            {
                using (Brush disabledBrush = new SolidBrush(Color.FromArgb(20, Color.Gray)))
                {
                    g.FillRectangle(disabledBrush, rect);
                }
            }
        }

        // 根据进度值获取颜色
        private Color GetProgressColor(int progress)
        {
            if (progress < 30) return Color.FromArgb(255, 100, 100);
            if (progress < 70) return Color.FromArgb(255, 200, 50);
            return Color.FromArgb(100, 200, 100);
        }

        // 模拟进度更新
        private void StartProgressSimulation(DataGridViewRow row, int taskId)
        {
            var timer = new System.Windows.Forms.Timer();
            timer.Interval = 200;
            var random = new Random();

            timer.Tick += (s, e) =>
            {
                if (row.Cells["TaskStatus"].Value?.ToString() == "进行中")
                {
                    int currentProgress = Convert.ToInt32(row.Cells["Progress"].Value);
                    if (currentProgress < 100)
                    {
                        int newProgress = currentProgress + random.Next(1, 5);
                        if (newProgress > 100) newProgress = 100;

                        row.Cells["Progress"].Value = newProgress;

                        if (newProgress >= 100)
                        {
                            row.Cells["TaskStatus"].Value = "已完成";
                            timer.Stop();
                        }

                        dataGridView1.InvalidateCell(row.Cells["Progress"]);
                    }
                    else
                    {
                        timer.Stop();
                    }
                }
                else
                {
                    timer.Stop();
                }
            };

            timer.Start();
        }

        private void DataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                var row = dataGridView1.Rows[e.RowIndex];

                if (e.ColumnIndex == dataGridView1.Columns["TaskStatus"].Index)
                {
                    string status = e.Value?.ToString();

                    switch (status)
                    {
                        case "进行中":
                            row.DefaultCellStyle.BackColor = Color.FromArgb(240, 255, 240);
                            break;
                        case "已完成":
                            row.DefaultCellStyle.BackColor = Color.FromArgb(240, 240, 255);
                            break;
                        case "已暂停":
                            row.DefaultCellStyle.BackColor = Color.FromArgb(255, 255, 240);
                            break;
                        default:
                            row.DefaultCellStyle.BackColor = Color.White;
                            break;
                    }
                }
            }
        }

        private void 刷新任务ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetupDataGridView();
            LoadDataFromDatabase();
        }

        private void 新建任务ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            HomeForm.TaskAdd task = new TaskAdd();
            task.ShowDialog();
        }

        private void 删除任务ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count == 0)
            {
                MessageBox.Show("请先选择要删除的任务行！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 检查是否有进行中的任务被选中
            var runningTasks = dataGridView1.SelectedRows
                .Cast<DataGridViewRow>()
                .Where(row => row.Cells["TaskStatus"].Value?.ToString() == "进行中")
                .Select(row => row.Cells["TaskName"].Value.ToString())
                .ToList();

            if (runningTasks.Count > 0)
            {
                MessageBox.Show($"以下任务正在进行中，无法删除：\n{string.Join("\n", runningTasks)}", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 确认删除
            var result = MessageBox.Show($"确定要删除选中的 {dataGridView1.SelectedRows.Count} 个任务吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                bool allSuccess = true;
                List<string> failedTasks = new List<string>();

                // 倒序删除，避免索引问题
                for (int i = dataGridView1.SelectedRows.Count - 1; i >= 0; i--)
                {
                    DataGridViewRow row = dataGridView1.SelectedRows[i];
                    int taskId = Convert.ToInt32(row.Cells["TaskId"].Value);
                    string taskName = row.Cells["TaskName"].Value.ToString();

                    if (!DeleteTaskFromDatabase(taskId))
                    {
                        allSuccess = false;
                        failedTasks.Add(taskName);
                    }
                    else
                    {
                        dataGridView1.Rows.Remove(row);
                    }
                }

                if (allSuccess)
                {
                    MessageBox.Show($"已成功删除 {dataGridView1.SelectedRows.Count} 个任务", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show($"部分任务删除失败：\n{string.Join("\n", failedTasks)}", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        private void 账号管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            HomeForm.Users users = new HomeForm.Users();
            users.ShowDialog();
        }

        private void 代理管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            HomeForm.Proxy proxy = new HomeForm.Proxy();
            proxy.ShowDialog();
        }

        private void 扫描设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            HomeForm.Scan scan = new HomeForm.Scan();
            scan.ShowDialog();
        }
        /// <summary>
        /// 退出系统
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 退出系统ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void 查看详情ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            HomeForm.VulnerInfo info = new HomeForm.VulnerInfo();
            info.ShowDialog();
        }

        private void 启动任务ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private async void 端口验证ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //string url = "https://www.baidu.com"; // 替换为你想要查询的URL

            //string title = await Services.Tl_DomainScan.GetPageTitleAsync(url);
            //Console.WriteLine($"网页标题: {title}");

            //string serviceInfo = await Services.Tl_DomainScan.GetWebServiceInfoAsync(url);
            //Console.WriteLine($"服务信息: {serviceInfo}");
            var crawler = new WebsiteStructureCrawler(maxDepth: 1);

            try
            {
                var structure = await crawler.GetWebsiteStructureAsync("https://fanyi.baidu.com");
                structure.PrintStructure();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"发生错误: {ex.Message}");
            }
            finally
            {
                crawler.Dispose();
            }
        }
    }
}